<template>
  <div class="content">
    <div class="upload">
      <el-upload
        class="upload-demo"
        action
        accept=".xlsx, .xls"
        multiple
        :on-change="handle"
        :auto-upload="false"
      >
        <el-button type="primary">上传文件</el-button>
        <template #tip>
          <div class="el-upload__tip"></div>
        </template>
      </el-upload>
    </div>
    <div>
      <el-progress :percentage="percentage" :status="status" v-show="parshow" />
    </div>
    <div class="notice">
      <div class="flex" v-for="(item, index) in errList" :key="index">
        <div>{{ item.line }}：</div>
        <div>{{ item.message }}</div>
      </div>
    </div>
    <el-button class="close" type="default" @click="close">关闭</el-button>
  </div>
</template>
  
<script setup>
import { ref } from "vue";
import { read, utils } from "xlsx";
import { readFile, delay } from "@/utils/plugs";
import http from "@/api/index";

const emit = defineEmits(['closefile'])

let percentage = ref(0);
let status = ref("exception");
let errList = ref([]);
let parshow = ref(false);

const close = ()=>{
  emit('closefile')
}
// 采集EXCEL数据
const handle = async (ev) => {
  parshow.value = true;
  let file = ev.raw;
  if (!file) return;

  // 读取FILE中的数据
  let data = await readFile(file);
  let workbook = read(data, { type: "binary" });
  let worksheet = workbook.Sheets[workbook.SheetNames[0]];
  worksheet.A1.w = "name";
  worksheet.B1.w = "barcode";
  worksheet.C1.w = "price";
  worksheet.D1.w = "originalprice";
  worksheet.E1.w = "unit";
  worksheet.F1.w = "typename";
  worksheet.G1.w = "specifi";
  worksheet.H1.w = "mainbarcode";

  data = utils.sheet_to_json(worksheet);

  addProduct(data);
  return
};

const addProduct = async (data, ind = 0) => {
  percentage.value = Math.round(((ind + 1) / data.length) * 100);
  if (percentage.value == 100) status.value = "success";

  if (ind >= data.length) return;
  var params = {
    name: data[ind].name,
    barcode: data[ind].barcode,
    price: data[ind].price,
    originalprice: data[ind].originalprice,
    unit: data[ind].unit,
    typename: data[ind].typename,
    specifi: data[ind].specifi,
    mainbarcode: data[ind].mainbarcode,
  };
  var result = await http.batchProduct({ params });

  if (result.data.status == 0) {
    var obj = {
      line: `第${ind + 1}行`,
      message: result.data.message,
    };
    errList.value.push(obj);
  }
  
  delay(100)
  ind++;
  addProduct(data, ind);
};
</script>
<style scoped>
@import "@/assets/css/importfile.css";
</style>